import React, { useState } from 'react';
import {
  Card,
  Typography,
  Tag,
  Space,
  Button,
  Divider,
  Row,
  Col,
  Avatar,
  Tooltip,
  Badge,
  List,
  Form,
  Input,
  message,
  Affix
} from 'antd';
import {
  EditOutlined,
  LikeOutlined,
  LikeFilled,
  ShareAltOutlined,
  DownloadOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  UserOutlined,
  TagOutlined,
  FileTextOutlined,
  CommentOutlined
} from '@ant-design/icons';
import { DocumentVO } from '../../../api/document';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;

interface DocumentDetailProps {
  document: DocumentVO | null;
  onEdit: (doc: DocumentVO) => void;
}

const DocumentDetail: React.FC<DocumentDetailProps> = ({
  document,
  onEdit,
}) => {
  const [liked, setLiked] = useState(false);
  const [commentForm] = Form.useForm();
  const [comments, setComments] = useState<any[]>([]);

  if (!document) {
    return <div>暂无数据</div>;
  }

  // 状态映射
  const statusMap = {
    0: { text: '草稿', color: 'default' },
    1: { text: '已发布', color: 'success' },
    2: { text: '已下线', color: 'error' },
  };

  // 点赞处理
  const handleLike = () => {
    setLiked(!liked);
    message.success(liked ? '取消点赞' : '点赞成功');
  };

  // 分享处理
  const handleShare = () => {
    navigator.clipboard.writeText(window.location.href);
    message.success('链接已复制到剪贴板');
  };

  // 下载文档
  const handleDownload = () => {
    message.success('下载功能待实现');
  };

  // 提交评论
  const handleSubmitComment = async () => {
    try {
      const values = await commentForm.validateFields();
      const newComment = {
        id: Date.now(),
        author: '当前用户',
        content: values.content,
        createTime: new Date().toISOString(),
        avatar: null,
      };
      setComments([newComment, ...comments]);
      commentForm.resetFields();
      message.success('评论成功');
    } catch (error) {
      message.error('评论失败');
    }
  };

  return (
    <div style={{ maxHeight: '80vh', overflow: 'auto' }}>
      {/* 文档头部信息 */}
      <Card>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          {/* 标题和状态 */}
          <div>
            <Space align="start">
              <Title level={3} style={{ margin: 0 }}>
                {document.title}
              </Title>
              <Tag color={statusMap[document.status as keyof typeof statusMap]?.color}>
                {statusMap[document.status as keyof typeof statusMap]?.text}
              </Tag>
              {document.isTop && (
                <Tag color="gold">置顶</Tag>
              )}
            </Space>
          </div>

          {/* 文档元信息 */}
          <Row gutter={24}>
            <Col span={6}>
              <Space>
                <UserOutlined />
                <Text>作者：{document.author}</Text>
              </Space>
            </Col>
            <Col span={6}>
              <Space>
                <ClockCircleOutlined />
                <Text>发布时间：{document.publishTime ? new Date(document.publishTime).toLocaleString() : '未发布'}</Text>
              </Space>
            </Col>
            <Col span={6}>
              <Space>
                <EyeOutlined />
                <Text>浏览量：{document.viewCount}</Text>
              </Space>
            </Col>
            <Col span={6}>
              <Space>
                <LikeOutlined />
                <Text>点赞数：{document.likeCount}</Text>
              </Space>
            </Col>
          </Row>

          {/* 标签 */}
          {document.tags && document.tags.length > 0 && (
            <div>
              <Space>
                <TagOutlined />
                <Text>标签：</Text>
                {document.tags.map((tag, index) => (
                  <Tag key={index} color="blue">
                    {tag}
                  </Tag>
                ))}
              </Space>
            </div>
          )}

          {/* 摘要 */}
          {document.summary && (
            <div>
              <Text type="secondary">{document.summary}</Text>
            </div>
          )}

          {/* 操作按钮 */}
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => onEdit(document)}
            >
              编辑
            </Button>
            <Button
              icon={liked ? <LikeFilled /> : <LikeOutlined />}
              onClick={handleLike}
              style={{ color: liked ? '#1890ff' : undefined }}
            >
              {liked ? '已点赞' : '点赞'}
            </Button>
            <Button icon={<ShareAltOutlined />} onClick={handleShare}>
              分享
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleDownload}>
              下载
            </Button>
          </Space>
        </Space>
      </Card>

      <Divider />

      {/* 文档内容 */}
      <Card title={<Space><FileTextOutlined />文档内容</Space>}>
        <div
          style={{
            whiteSpace: 'pre-wrap',
            lineHeight: '1.8',
            fontSize: '14px',
            minHeight: '200px',
          }}
        >
          {document.content}
        </div>
      </Card>

      {/* 附件列表 */}
      {(document as any).attachments && (document as any).attachments.length > 0 && (
        <>
          <Divider />
          <Card title="附件">
            <List
              dataSource={(document as any).attachments}
              renderItem={(item: any) => (
                <List.Item
                  actions={[
                    <Button
                      type="link"
                      icon={<DownloadOutlined />}
                      onClick={() => window.open(item.url)}
                    >
                      下载
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<FileTextOutlined />} />}
                    title={item.name}
                    description={`文件大小：${item.size || '未知'}`}
                  />
                </List.Item>
              )}
            />
          </Card>
        </>
      )}

      {/* 评论区域 */}
      <Divider />
      <Card title={<Space><CommentOutlined />评论区</Space>}>
        {/* 评论表单 */}
        <Form form={commentForm} onFinish={handleSubmitComment}>
          <Form.Item
            name="content"
            rules={[{ required: true, message: '请输入评论内容' }]}
          >
            <TextArea
              rows={3}
              placeholder="请输入您的评论..."
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              发表评论
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        {/* 评论列表 */}
        <List
          dataSource={comments}
          locale={{ emptyText: '暂无评论' }}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Space>
                    <Text strong>{item.author}</Text>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {new Date(item.createTime).toLocaleString()}
                    </Text>
                  </Space>
                }
                description={item.content}
              />
            </List.Item>
          )}
        />
      </Card>

      {/* 浮动操作栏 */}
      <Affix offsetBottom={20}>
        <div style={{ textAlign: 'right' }}>
          <Space direction="vertical">
            <Tooltip title="返回顶部">
              <Button
                shape="circle"
                icon={<EyeOutlined />}
                onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
              />
            </Tooltip>
            <Tooltip title="点赞">
              <Button
                shape="circle"
                icon={liked ? <LikeFilled /> : <LikeOutlined />}
                onClick={handleLike}
                style={{ color: liked ? '#1890ff' : undefined }}
              />
            </Tooltip>
          </Space>
        </div>
      </Affix>
    </div>
  );
};

export default DocumentDetail;